package com.corpcredit.dao.hibernate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.corpcredit.dao.LookupDao;
import com.corpcredit.model.GlryCwfzr;
import com.corpcredit.model.Jbqk;
import com.corpcredit.model.Role;

/**
 * Hibernate implementation of LookupDao.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class LookupDaoHibernate extends UniversalDaoHibernate implements LookupDao {

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<Role> getRoles() {
        log.debug("Retrieving all role names...");

        return getHibernateTemplate().find("from Role order by name");
    }

	public List findAllByJbqkID(Class clazz, Long jbqkID) {
		if(jbqkID == null)
		{
			return Collections.EMPTY_LIST;
		}
		String hql = "from "+ clazz.getName() +" where jbq_ID  = '"+ jbqkID +"'";
		return getHibernateTemplate().find( hql );
	}

	public Object findByJbqkID(Class clazz, Long jbqkID) {
		List result = findAllByJbqkID(clazz, jbqkID);
		if(result.isEmpty())
			return null;
		else
		return result.get(0);
	}
	
	public Object findByRyid(String clazz,String ryid)
	{
		if(clazz==null||ryid==null)
		{
			return null;
		}
		String hql = "from "+ clazz +" where ryid  = '"+ ryid +"'";
		if(getHibernateTemplate().find( hql ).size()==0)
		{
			return null;
		}else
		{
			return getHibernateTemplate().find( hql ).get(0);
		}
	}
	
	public List findGlryCwfzrByJqbkID(Long jbqkID)
	{
		if(jbqkID == null)
		{
			return Collections.EMPTY_LIST;
		}
		String hql = "from  GlryCwfzr gl where gl.glry in (from Glry g where g.jbqk='"+jbqkID+"')";
		return getHibernateTemplate().find( hql );
	}
	
	public List<Jbqk> findJbqks( String qyqc, String yyzzzch, String ssqy, Long hyflID )
	{
	    List<Jbqk> results = new ArrayList<Jbqk>();
	    String hql = "from Jbqk where";
	    StringBuffer query = new StringBuffer();
        if( qyqc != null && (!qyqc.trim().equals( "" )) )
        {
            if( !query.toString().equals( "" ) )
                query.append( " or" );
            query.append( " qyqc like '" + qyqc + "%'" );
        }
        if( yyzzzch != null && (!yyzzzch.trim().equals( "" )) )
        {
            if( !query.toString().equals( "" ) )
                query.append( " or" );
            query.append( " yyzzzch like '" + yyzzzch + "%'" );
        }
        if( ssqy != null && (!ssqy.trim().equals( "" )) )
        {
            if( !query.toString().equals( "" ) )
                query.append( " or" );
            query.append( " ssqy like '" + ssqy + "%'" );
        }
        if( hyflID != null && hyflID.longValue()!= 0  )
        {
            if( !query.toString().equals( "" ) )
                query.append( " and" );
            query.append( " hyf_ID = " + hyflID  );
        }
	    hql += query.toString();
        log.debug( "hql: " + hql );
        return getHibernateTemplate().find( hql );
	}
}
